#include "uart.c"
#include <regx52.h>

unsigned int get_timer0_value()
{
    unsigned char high, low;

    do
    {
        high = TH0;
        low = TL0;
    } while (high != TH0);

    // (high << 8) 表达式数据类型是int
    return (high << 8) | low;
}

void timer0_init()
{
    // timer0 模式1: 使用TH0+TL0 计数
    TMOD &= 0xF0;
    TMOD |= 0x01;

    // 启动Timer0，启动之后TH0+TL0计数
    TR0 = 1;
    // timer0的中断使能
    ET0 = 1;
    // 中断总开关
    EA = 1;
    // 调整中断优先级，需要在timer0中断调用串口打印设置优先级
    PT0 = 1;
}

sbit BTN_RAND = P2 ^ 1;
sbit BTN_SEED = P2 ^ 2;
sbit BTN_THTL = P2 ^ 3;

unsigned int timer_seed = 0x1234;

unsigned int timer_rand()
{
    timer_seed = (timer_seed * 12345 + 67890) % 65535;
    return timer_seed;
}

void main()
{
    uart_init();
    timer0_init();
    while (1)
    {
        if (BTN_RAND == 0)
        {
            while (BTN_RAND == 0)
            {
            }
            printf("RAND=%u\n", timer_rand());
            printf("game seed=%u\n", timer_seed);
        }

        if (BTN_SEED == 0)
        {
            while (BTN_SEED == 0)
            {
            }
            printf("game seed=%u\n", timer_seed);
        }
        if (BTN_THTL == 0)
        {
            while (BTN_THTL == 0)
            {
            }
            printf("TH0TL0=0x%04x\n", get_timer0_value());
        }
    }
}
